package com.java.multipledatasource.registered;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author hu
 * @version 1.0
 * @date 2020/12/30 0030 下午 3:00
 * @description
 */
@Component
public class CheckParamsService implements ApplicationContextAware, InitializingBean {

    private  ApplicationContext applicationContext;
    private  List<RegisteredParamCheckService> registeredParamCheckServiceList = new ArrayList<>(10);

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
     this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, RegisteredParamCheckService> beans = applicationContext.getBeansOfType(RegisteredParamCheckService.class);
        beans.forEach((key, value) -> registeredParamCheckServiceList.add(value));
    }

    public void checkByField(byte code, Object obj) {
        for (RegisteredParamCheckService paramCheckService : registeredParamCheckServiceList) {
            if (paramCheckService.checkCode(code)) {
                paramCheckService.checkByFieldRules(obj);
            }
        }
    }


    public void checkIsExit(byte code, Object obj) {
        for (RegisteredParamCheckService paramCheckService : registeredParamCheckServiceList) {
            if (paramCheckService.checkCode(code)) {
                paramCheckService.checkIsExist(obj);
            }
        }
    }
}
